package com.service;

import com.bean.GoodImg;
import com.bean.GoodMessage;
import com.bean.User;
import com.config.MinioAddr;
import com.mapper.GoodImgMapper;
import com.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mapper.GoodMessageMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodMessageServiceImpl extends ServiceImpl<GoodMessageMapper, GoodMessage> implements GoodMessageService {

    @Autowired
    GoodMessageMapper goodMessageMapper;

    @Autowired
    GoodImgMapper goodImgMapper;

    @Autowired
    UserMapper userMapper;


    /**
     * 根据发送用户id查询所有未读互动消息
     *
     * @param userId
     * @return
     */
    @Override
    public List<Map<String, Object>> getAllUncheckedMessagesBySendToUserId(int userId) {

        Map<String, Object> map = new HashMap<>();
        map.put("send_to_user_id", userId);
//        map.put("message_checked", false);
        List<GoodMessage> goodMessages = goodMessageMapper.selectByMap(map);

        // 筛选非自己的互动消息
        List<GoodMessage> goodMessagesByOthers = new ArrayList<>();
        for (GoodMessage goodMessage : goodMessages) {
            if (!goodMessage.getUserId().equals(goodMessage.getSendToUserId())) {
                goodMessagesByOthers.add(goodMessage);
            }
        }

        // 获取用户id
        List<Map<String, Object>> goodMessagesList = new ArrayList<>();
        // 倒序 新消息靠前
        for (int i = goodMessagesByOthers.size()-1; i >= 0; i--) {
            GoodMessage goodMessage = goodMessagesByOthers.get(i);
            User user = userMapper.selectById(goodMessage.getUserId());

            Map<String, Object> messageMap = new HashMap<>();

            // 获取宝贝相关信息
            Map<String, Object> map1 = new HashMap<>();
            map1.put("good_id", goodMessage.getGoodId());
            List<GoodImg> goodImgs = goodImgMapper.selectByMap(map1);
            if (goodImgs.size() != 0) {
                messageMap.put("goodImg", MinioAddr.IMG_PATH + goodImgs.get(0).getSrc());
            }

            messageMap.put("goodId", goodMessage.getGoodId());

            // 获取用户相关信息
            messageMap.put("userId", goodMessage.getUserId());
            messageMap.put("nickName", user.getNickName());
            messageMap.put("icon", MinioAddr.IMG_PATH + user.getIcon());
            messageMap.put("date", goodMessage.getDate());
            messageMap.put("text", goodMessage.getText());
            messageMap.put("sendType", goodMessage.getSendType());
            messageMap.put("msgChecked", goodMessage.getMessageChecked());

            goodMessagesList.add(messageMap);
        }

        return goodMessagesList;
    }
}




